package com.datastructures2.链表;

/**
 * @author MaoLin Wang
 * @date 2020/10/6 9:17 下午
 */
public class 倒数第k个节点 {
    /**
     * 倒数第k个 那就让fast先走k-1个  到第k个的时候 fast和slow一起走 当fast走到最后 slow正好在倒数第k个
     * @param listNode
     * @param k
     * @return
     */
    public static ListNode kofback(ListNode listNode,int k){
        if (listNode==null || k <0){
            return null;
        }
        ListNode fast=listNode;
        ListNode slow=listNode;

        int count=0;
        while (count<k-1){
            fast=fast.next;
            count++;
        }
        while (fast!=null &&fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;

    }

    public static ListNode deleteN(ListNode listNode,int n){
        if (listNode==null || n<0){
            return listNode;
        }
        ListNode fast=listNode;
        ListNode slow=listNode;

        int count=0;
        while (count<n){
            count++;
            fast=fast.next;
        }
        ListNode delepre=slow;
        while (fast.next!=null){
            fast=fast.next;
            delepre=delepre.next;
        }
        delepre.next=delepre.next.next;
        return slow;
    }

    public static void main(String[] args) {
        ListNode node=new ListNode(3);
        ListNode node1=new ListNode(4);
        ListNode node2=new ListNode(5);
        node.next=node1;
        node1.next=node2;
        System.out.println(kofback(node,4));
    }
}
